/*
 * @Description:
 * @Author: fhw
 * @Date: 2022-12-26 13:54:57
 */
import { Injectable } from '@nestjs/common';
import { OssService } from 'src/common/oss/oss.service';
import { throwHttp } from 'src/utlis';
import * as OSS from 'ali-oss';
import STS from 'ali-oss/lib/sts';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class UploadService {
  private ossClient: OSS;
  private stsClient: STS;
  private ossConfig = {
    accessKeyId: this.configService.get<string>('OSS_ACCESS_KEY_ID'),
    accessKeySecret: this.configService.get<string>('OSS_ACCESS_KEY_SECRET'),
    region: this.configService.get<string>('OSS_REGION'),
    bucket: this.configService.get<string>('OSS_BUCKET'),
    roleArn: this.configService.get<string>('OSS_ROLE_ARN'),
    endpoint: this.configService.get<string>('OSS_ENDPOINT'),
  }
  constructor(private readonly ossService: OssService,
    private configService: ConfigService
  ) {
    this.ossClient = new OSS(this.ossConfig);
    this.stsClient = new OSS.STS({
      accessKeyId: this.ossConfig.accessKeyId,
      accessKeySecret: this.ossConfig.accessKeySecret,
    });
  }
  // 上传照片
  async uploadImage(file: any): Promise<any> {
    try {
      const ossUrl = await this.ossService.putOssFile(
        `/image/${file.originalname}`,
        file.path,
      );
      return {
        filename: file.originalname,
        url: ossUrl,
      };
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /**
   * 获取 OSS 临时访问授权
   */
  async getTemporaryCredentials() {

    // 请求 STS 临时访问凭证
    const token = await this.stsClient.assumeRole(
      this.ossConfig.roleArn,
      '',
      3600, // Token 有效期，单位秒
    );

    return {
      accessKeyId: token.credentials.AccessKeyId,
      accessKeySecret: token.credentials.AccessKeySecret,
      securityToken: token.credentials.SecurityToken,
      expiration: token.credentials.Expiration,
      endpoint: this.ossConfig.endpoint,
      bucket: this.ossConfig.bucket,
    };
  }
}
